package com.spdd.mt.biz.manager.feishu;


import cn.hutool.core.util.StrUtil;
import com.spdd.mt.biz.config.AppConfig;
import com.spdd.mt.common.http.HttpUtil;
import com.spdd.mt.common.util.DateUtils;
import com.yomahub.tlog.context.TLogContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * 飞书通知 service
 */
@Slf4j
@Service("feiShuService")
public class FeiShuService {

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private AppConfig appConfig;

    @Resource
    private FeiShuConfig feiShuConfig;

    /**
     * 打印异常日志
     *
     * @param exception 异常信息
     */
    @Async
    public void sendExceptionMsg(Exception exception) {
        if (!feiShuConfig.getEnabled()) {
            return;
        }
        String msg = StrUtil.format(RobotConfig.exceptionTemplate,
                appConfig.getAppName(),
                appConfig.getAppName(),
                DateUtils.getCurrentDateTime(),
                TLogContext.getSpanId() + "_" + TLogContext.getTraceId(),
                exception.getMessage(),
                exception.getCause(),
                exception.getClass()
                // exception.getLocalizedMessage(),
                // exception.getStackTrace()
        );
        try {
            Long timestamp = DateUtils.currentSeconds();
            String sign = RobotSign.genSign(feiShuConfig.getKeyException(), timestamp);
            Map<String, String> postMap = new HashMap<>();
            postMap.put("timestamp", String.valueOf(timestamp));
            postMap.put("sign", sign);
            postMap.put("msg_type", "text");
            postMap.put("content", "{\"text\":\"" + msg + "\"}");

            Object response = httpUtil.postForm(feiShuConfig.getUrlException(), postMap, new ParameterizedTypeReference<>() {
            });
            log.info("msg response = {}", response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
